package com.pomr.service.record.Impl;

import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.pomr.dao.record.FamilyDao;
import com.pomr.model.health.FamilyRecord;
import com.pomr.model.health.FamilyRelation;
import com.pomr.service.record.FamilyService;
import com.pomr.util.page.Page;

@Service("familyServiceImpl")
public class FamilyServiceImpl implements FamilyService{
	
	@Autowired
	@Qualifier("familyDaoImpl")
	private FamilyDao familyDao;

	@Override
	@Transactional(rollbackFor=Exception.class)
	public boolean saveFamily(FamilyRecord fr) throws Exception {
		fr.setCreateTime(new Date());
		fr.setAgency(fr.getUser().getAgency());
		//先保存家庭信息
		Integer id = familyDao.addNumKey(fr);
		if(id>0){
			Set<FamilyRelation> fs = fr.getFamilyRelations();
			if(fs==null || fs.size()<=0){
				throw new Exception("没有户主");
			}
			Iterator<FamilyRelation> it = fs.iterator();
			while (it.hasNext()) {
				FamilyRelation s = it.next();
				s.setFamilyrecord_id(id);
				if(!familyDao.add(s)){
					throw new Exception("保存家庭关系信息失败");
				}
			}
		}else{
			throw new Exception("保存家庭信息失败");
		}
		
		return true;
	}

	@Override
	public Page<List<FamilyRecord>> searchFamilys(Page<List<FamilyRecord>> page, String tj) throws Exception {
		StringBuilder sb = new StringBuilder();
		sb.append("from FamilyRecord where id in (");
		sb.append("select fre.familyrecord_id from FamilyRelation fre where fre.personrecord.id in (");
		sb.append("select pre.id from PersonRecord pre where pre.name like '%"+tj+"%' or pre.idcard like '%"+tj+"%'))");
		System.out.println(sb.toString());
		List<FamilyRecord> rs = familyDao.findByHql(sb.toString());
		page = familyDao.showPage(sb.toString(), "select count(1) "+sb.toString(), page);
		return page;
	}

	@Override
	@Transactional(rollbackFor=Exception.class)
	public boolean deleteFamilys(List<String> ids) throws Exception {
		String hql = "";
		for(String id:ids){
			//删除家庭关系
			hql = "delete from FamilyRelation where familyrecord_id = "+Integer.valueOf(id);
			if(familyDao.editHql(hql)){
				
			}else{
				throw new Exception("删除家庭档案失败");
			}
			//删除家庭信息
			hql = "delete from FamilyRecord where id = "+Integer.valueOf(id);
			if(familyDao.editHql(hql)){
				
			}else{
				throw new Exception("删除家庭档案失败");
			}
		}
		return true;
	}

	@Override
	public FamilyRecord searchRecords(FamilyRecord record) throws Exception {
		String hql = "from FamilyRecord where id="+record.getId();
		List<FamilyRecord> records = familyDao.findByHql(hql);
		if(records==null || records.size()<=0){
			return null;
		}
		FamilyRecord frecord = records.get(0);
		Set<FamilyRelation> ss = frecord.getFamilyRelations();
		frecord.setFamilyRelations(ss);
		return frecord;
	}

	@Override
	@Transactional(rollbackFor=Exception.class)
	public boolean updateFamily(FamilyRecord fr) throws Exception {
		if(fr!=null){
			System.out.println(fr.getId());
			System.out.println(fr.getAddr());
			System.out.println(fr.getTel());
		}
		//先更新家庭信息
		if(familyDao.editEntity(fr)){
			//删除所有家庭关系信息
			familyDao.remove("delete from family_relation where familyrecord_id = "+fr.getId());
			
			Set<FamilyRelation> fs = fr.getFamilyRelations();
			if(fs==null || fs.size()<=0){
				return true;
			}
			Iterator<FamilyRelation> it = fs.iterator();
			while (it.hasNext()) {
				FamilyRelation s = it.next();
				s.setFamilyrecord_id(fr.getId());
				if(!familyDao.add(s)){
					throw new Exception("更新家庭关系信息失败");
				}
			}
		}else{
			throw new Exception("更新家庭信息失败");
		}
		
		return true;
	}

	@Override
	public Page<List<FamilyRecord>> searchFamilyInfo(Page<List<FamilyRecord>> page, String tj) throws Exception {
		String hql = "from FamilyRecord where id in (select familyrecord_id from FamilyRelation where personrecord.id="+tj+")";
		if(tj==null || "".equals(tj)){
			hql = "from FamilyRecord";
		}
		page = familyDao.showPage(hql, "select count(1) "+hql, page);
		return page;
	}
	
	@Transactional(rollbackFor=Exception.class)
	public boolean updateFamilyInfo(FamilyRecord fr)throws Exception{
		StringBuilder sb = new StringBuilder();
		sb.append("update FamilyRecord set ");
		if(fr.getProvince()!=null){
			sb.append("province.id = "+fr.getProvince().getId()+",");
		}
		if(fr.getCity()!=null){
			sb.append("city.id = "+fr.getCity().getId()+",");
		}
		if(fr.getCoutry()!=null){
			sb.append("coutry.id = "+fr.getCoutry().getId()+",");
		}
		sb.append("addr = '"+fr.getAddr()+"',");
		sb.append("tel = '"+fr.getTel()+"'");
		sb.append(" where id = "+fr.getId());
		return familyDao.editHql(sb.toString());
	}

	@Override
	public Page<List<FamilyRecord>> searchFamilyOfPersonInfo(Page<List<FamilyRecord>> page, String tj)
			throws Exception {
		if(tj==null || "".equals(tj)){
			throw new Exception("家庭档案信息缺失");
		}
		String hql = "from FamilyRelation fr left join fetch fr.personrecord where fr.familyrecord_id = "+tj;
		String hqll = "select count(1) from FamilyRelation where familyrecord_id = "+tj;
		page = familyDao.showPage(hql, hqll, page);
		return page;
	}

	@Override
	@Transactional(rollbackFor=Exception.class)
	public boolean saveRelation(FamilyRelation relation) throws Exception {
		
		return familyDao.add(relation);
	}

	@Override
	public boolean deleteRelations(List<String> ids) throws Exception {
		if(ids==null || ids.size()<=0){
			throw new Exception("删除家庭成员失败,请上传要删除的家庭成员信息");
		}
		//判断家庭成员关系 删除
		for(String id:ids){
			
			String hql = "delete from FamilyRelation where id = "+id;
			if(!familyDao.editHql(hql)){
				throw new Exception("删除家庭成员失败");
			}
		}
		return true;
	}

	@Override
	@Transactional(rollbackFor=Exception.class)
	public boolean switchRelation(String id,String fid) throws Exception {
		//查询户主
		String hql = "from FamilyRelation where familyrecord_id="+fid+" and relation.id=1";
		List<FamilyRelation> rs = familyDao.findByHql(hql);
		if(rs!=null && rs.size()>0){
			//将原户主关系设为未知
			hql = "update FamilyRelation set relation.id=12 where id = "+rs.get(0).getId();
			if(!familyDao.editHql(hql)){
				throw new Exception("原户主关系更改失败");
			}
		}
		
		//将成员设为户主
		hql = "update FamilyRelation set relation.id=1 where id="+id;
		if(!familyDao.editHql(hql)){
			throw new Exception("成员关系更改失败");
		}
		return true;
	}

}
